package cn.dlc.com.user.controller;

import cn.dlc.com.user.model.User;
import cn.dlc.com.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author 邓立川
 * @date 2021/11/21 10:15
 * @desc 当前类的描述信息
 */
@RestController
// 后面这个用来设置编码的
@RequestMapping(value = "user",produces = {"text/plain;charset=UTF-8"})
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/login")
    public String authentication(User user, HttpSession session) {

        System.out.println(user.getUsername());

        User authentication = userService.authentication(user);
        // 登录成功，添加session
        session.setAttribute("user_", authentication);
        return authentication.getUsername() + "登录成功";
    }

    @GetMapping("logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "退出成功";
    }

    @GetMapping("r/r1")
    public String resource1(HttpSession session){

        Object user_ = session.getAttribute("user_");
        if(user_ != null) {
            User user = (User)user_;
            return user.getUsername() + "来了。。。r1";
        } else {
            return "匿名访问";
        }
    }

    @GetMapping("r/r2")
    public String resource2(HttpSession session){

        Object user_ = session.getAttribute("user_");
        if(user_ != null) {
            User user = (User)user_;
            return user.getUsername() + "来了。。。r2";
        } else {
            return "匿名访问";
        }
    }
}
